import { reactive } from 'vue'

let _id = 0
const timers = new Map<string, number>()

export const notificationState = reactive({
  items: [] as Notify.NotificationItem[]
})

export function addNotification(opt: Notify.NotificationOptions): Notify.NotificationItem {
  const id = `${Date.now()}_${_id++}`
  const item: Notify.NotificationItem = {
    id,
    level: opt.level ?? 'in-app',
    variant: opt.variant ?? 'info',
    position: opt.position ?? 'top-right',
    title: opt.title ?? '',
    message: opt.message ?? '',
    icon: opt.icon ?? '',
    actions: opt.actions ?? [],
    timeout: typeof opt.timeout === 'number' ? opt.timeout : 5000,
    closeable: opt.closeable ?? true,
    createdAt: Date.now(),
    x: opt.x,
    y: opt.y,
    ext: opt.ext
  }
  notificationState.items.push(item)
  console.log('添加通知:', item)
  if (item.timeout && item.timeout > 0) {
    const t = window.setTimeout(() => removeNotification(id), item.timeout)
    timers.set(id, t)
  }

  return item
}

export function removeNotification(id: string) {
  const idx = notificationState.items.findIndex(n => n.id === id)
  console.log('移除通知:', id, idx)
  if (idx !== -1) {
    notificationState.items.splice(idx, 1)
  }
  const t = timers.get(id)
  if (t) {
    clearTimeout(t)
    timers.delete(id)
  }
}

export function clearNotifications(position?: Notify.NotificationPosition) {
  const ids = notificationState.items
    .filter(n => (position ? n.position === position : true))
    .map(n => n.id)
  ids.forEach(removeNotification)
}
